<template>
  <main-layout>
    <div class="chart-container">
      <div id="chart-left" style="width: 50%; height: 500px; float: left"></div>
      <div
        id="chart-right"
        style="width: 50%; height: 500px; float: right"
      ></div>
    </div>
  </main-layout>
</template>

<script>
import MainLayout from "@/components/Layout.vue";
import * as echarts from "echarts";

export default {
  name: "DoubleCharts",
  components: {
    MainLayout,
  },
  data() {
    return {
      leftChart: null,
      rightChart: null,
    };
  },
  mounted() {
    this.initLeftChart();
    this.initRightChart();
  },
  methods: {
    initLeftChart() {
      this.leftChart = echarts.init(document.getElementById("chart-left"));

      const option = {
        title: {
          text: "Column Chart",
        },
        xAxis: {
          type: "category",
          data: ["大豆", "玉米", "大米", "牛肉", "猪肉", "白菜"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: [5, 20, 36, 10, 10, 20],
            type: "bar",
          },
        ],
      };

      this.leftChart.setOption(option);
      window.addEventListener("resize", this.handleLeftResize);
    },
    initRightChart() {
      this.rightChart = echarts.init(document.getElementById("chart-right"));

      const option = {
        title: {
          text: "Bar Chart",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {},
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.01],
        },
        yAxis: {
          type: "category",
          data: ["湖南", "四川", "陕西", "云南", "西藏", "农产品（吨）"],
        },
        series: [
          {
            name: "2022年",
            type: "bar",
            data: [18203, 23489, 29034, 104970, 131744, 630230],
          },
          {
            name: "2023年",
            type: "bar",
            data: [19325, 23438, 31000, 121594, 134141, 681807],
          },
        ],
      };

      this.rightChart.setOption(option);
      window.addEventListener("resize", this.handleRightResize);
    },
    handleLeftResize() {
      if (this.leftChart) {
        this.leftChart.resize();
      }
    },
    handleRightResize() {
      if (this.rightChart) {
        this.rightChart.resize();
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleLeftResize);
    window.removeEventListener("resize", this.handleRightResize);
    if (this.leftChart) {
      this.leftChart.dispose();
    }
    if (this.rightChart) {
      this.rightChart.dispose();
    }
  },
};
</script>

<style scoped>
.chart-container {
  width: 100%;
  overflow: hidden; /* 清除浮动 */
}
</style>